﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Configuration;
using System.Data.SqlClient;

using ECS.DAL;
using ECS.DAL.Entity;
using ECS.DAL.Component;
using ECS.Framework;

namespace E_ICS.E_ICS
{
    public partial class frmEditDim : Form
    {
        #region private properties
        private DimensionRecordComponent _dataComponent = null;
        private SortableBindingList<DimensionRecord> _gridSource = new SortableBindingList<DimensionRecord>();
        private bool _isLoadedData = false;
        //SqlConnection sqlCon = new SqlConnection(ConfigurationManager.ConnectionStrings["con3"].ConnectionString);
        //DataSet dtDimDetail = null;
        //string dimension_id, length, width, height, piece_count;
        //string appId = ConfigurationManager.AppSettings["appID"];
        //string device = ConfigurationManager.AppSettings["device"];
        //DataSet datasetInsert = null;
        //DataSet datasetUpdate = null;
        //DataSet dataset = null;
        //int countpass = 0;
        //int allpass = 0;
        #endregion

        #region form events
        public frmEditDim()
        {
            InitializeComponent();
        }
        /// <summary>
        /// close form
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        /// <summary>
        /// load data to grid
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void frmEditDim_Load(object sender, EventArgs e)
        {
            SetScreen();
            try
            {
                _dataComponent = new DimensionRecordComponent();
                showdgvDimensionDisplay();
                setRowNumber(dgvDimension);
                _isLoadedData = true;
            }
            catch (Exception ex)
            {
                CommonMessageBox.ShowMessageError(ex);
            }
        }
        /// <summary>
        /// save data then close
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// 
         private void SetScreen()
        {
            this.Text = CommonResourceString.GetResourseValue("scn_EditDim_Name");
            btnSave.Text = CommonResourceString.GetResourseValue("scn_EditDim_btnSave");
            btnCancel.Text = CommonResourceString.GetResourseValue("scn_EditDim_btnCancel");
                            
          
        }
        //kung
        //kung
        private void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                CheckSaveChanged();
                
                
                this.Close();
            }
            catch (Exception ex)
            {
                CommonMessageBox.ShowMessageError(ex);
            }
        }

        private void GetPcs()
        {
            ViewEditWeightId.inteditPieces = 0;
            try
            {
                int dgvDimensionCount = dgvDimension.Rows.Count;
                if (dgvDimensionCount > 0)
                {
                    for (int i = 0; i < dgvDimensionCount; i++)
                    {
                        ViewEditWeightId.inteditPieces += Convert.ToInt32(dgvDimension.Rows[i].Cells[3].Value);
                    }
                }
            }
            catch (Exception ex)
            {
                
                CommonMessageBox.ShowMessageError(ex);
            }
        }
        /// <summary>
        /// delete row
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgvDimension_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                if (_gridSource.Count > 0)
                {
                    if (e.ColumnIndex == dgvDimension.Columns["btnDelete"].Index && e.RowIndex >= 0)    // Delete Dim
                    {
                        if (CommonMessageBox.ShowMessageConfirmDelete() == DialogResult.Yes)
                        {
                            if (_gridSource[e.RowIndex].GetObjectSate() != OBJECT_STATE.Insert)
                            {
                                DimensionRecord obj = _gridSource[e.RowIndex];
                                obj.AppId = GlobalVariable.user.ApplicationID;
                                obj.UserId = GlobalVariable.user.UserID;
                                obj.Device = GlobalVariable.user.Device;
                                obj.DeleteObject();
                                _dataComponent.Delete((ObjectContext)_gridSource[e.RowIndex]);
                            }
                            _gridSource.RemoveAt(e.RowIndex);
                            GetPcs();
                            this.DialogResult = DialogResult.Yes;
                            //setRowNumber((DataGridView)sender);
                        }
                    }
                }
                //if (e.ColumnIndex == dgvDimension.Columns["btndel"].Index && e.RowIndex >= 0)    // Delete Dim
                //{
                //    //string temp = dgvDimension.Rows[e.RowIndex].Cells[3].Value.ToString();

                //    //string dim_id = dgvDimension.Rows[e.RowIndex].Cells[0].Value.ToString();
                //    //dgvWHInventory
                //    if (CommonMessageBox.ShowMessageConfirmDelete() == DialogResult.Yes)
                //    {
                //        //SqlCommand cmd = new SqlCommand();
                //        //cmd.CommandText = "usp_DeleteDimensionRecord";
                //        //cmd.CommandType = CommandType.StoredProcedure;
                //        //cmd.Connection = sqlCon;
                //        //cmd.Parameters.AddWithValue("@in_vchApplicationID", appId);
                //        //cmd.Parameters.AddWithValue("@in_vchDimensionID", dim_id);

                //        //cmd.Parameters.AddWithValue("@in_vchDevice", device);
                //        //cmd.Parameters.AddWithValue("@in_vchUserID", GlobalVariable.userName);

                //        //sqlCon.Open();
                //        //SqlDataAdapter da = new SqlDataAdapter(cmd);
                //        //dataset = new DataSet();
                //        //da.Fill(dataset, "DeleteDimensionRecord");
                //        //string status = dataset.Tables[0].Rows[0]["Status"].ToString();
                //        //if (status == "PASS")
                //        //{

                //        //}
                //        //else
                //        //{
                //        //    MessageBox.Show(status);
                //        //}
                //        //sqlCon.Close();

                //        //dgvDimension.Rows.RemoveAt(e.RowIndex);
                //    }
                //}
            }
            catch (Exception ex)
            {
                CommonMessageBox.ShowMessageError(ex);
            }
        }
        /// <summary>
        /// validate input numeric value in datagrid
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgvDimension_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
        {
            try
            {
                if (_gridSource.Count > 0)
                {
                    if (e.ColumnIndex == dgvDimension.Columns["L"].Index || e.ColumnIndex == dgvDimension.Columns["W"].Index
                        || e.ColumnIndex == dgvDimension.Columns["H"].Index || e.ColumnIndex == dgvDimension.Columns["PCS"].Index)
                    {
                        if (!Utilities.IsNumeric(e.FormattedValue))
                        {
                            //CommonMessageBox.ShowMessageError(CommonResourceString.GetResourceString(CommonResourceString.ConstantString.INVALID_NUMBER_FORMAT));
                            e.Cancel = true;
                        }
                    }
                }

            }
            catch (Exception ex)
            {
                CommonMessageBox.ShowMessageError(ex);
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgvDimension_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
        {
            try
            {
                if (_isLoadedData)
                {
                    DataGridView dgv = (DataGridView)sender;
               
                    if (dgv.Rows.Count > 0)
                    {
                        //kung
                        setRowNumber(dgvDimension);
                        dgv.Rows[e.RowIndex].HeaderCell.Value = String.Format("{0}", e.RowIndex +1);
                        //dgv.Rows[e.RowIndex - 1].HeaderCell.Value = String.Format("{0}", e.RowIndex);
                    }
                }
            }
            catch (Exception ex)
            {
                CommonMessageBox.ShowMessageError(ex);
            }
        }
        #endregion

        #region private methods

        #endregion
        /// <summary>
        /// setup gridview
        /// </summary>
        public void showdgvDimensionDisplay()
        {
            DimensionRecord condition = new DimensionRecord();
            condition.SlipId = ViewEditWeightSlip.slip_id;
            List<ObjectContext> _dataList = _dataComponent.Search(condition);
            foreach (ObjectContext item in _dataList)
            {
                _gridSource.Add((DimensionRecord)item);
            }
            dgvDimension.AutoGenerateColumns = false;
            dgvDimension.Columns.Add("L", "L");
            dgvDimension.Columns[0].DefaultCellStyle.Format = "#,##0";
            dgvDimension.Columns[0].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            dgvDimension.Columns[0].DataPropertyName = "Length"; //condition.Length
            //dgvDimension.Columns[0].SortMode = DataGridViewColumnSortMode.Automatic;
            dgvDimension.Columns.Add("W", "W");
            dgvDimension.Columns[1].DefaultCellStyle.Format = "#,##0";
            dgvDimension.Columns[1].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            dgvDimension.Columns[1].DataPropertyName = "Width"; //condition.Width
            //dgvDimension.Columns[1].SortMode = DataGridViewColumnSortMode.Automatic;
            dgvDimension.Columns.Add("H", "H");
            dgvDimension.Columns[2].DefaultCellStyle.Format = "#,##0";
            dgvDimension.Columns[2].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            dgvDimension.Columns[2].DataPropertyName = "Height"; //condition.Height
            //dgvDimension.Columns[2].SortMode = DataGridViewColumnSortMode.Automatic;
            dgvDimension.Columns.Add("PCS", "PCS");
            dgvDimension.Columns[3].DefaultCellStyle.Format = "#,##0";
            dgvDimension.Columns[3].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            dgvDimension.Columns[3].DataPropertyName = "PieceCount"; //condition.PieceCount
            //dgvDimension.Columns[3].SortMode = DataGridViewColumnSortMode.Automatic;
            //this.dgvDimension.Columns[3].SortMode = DataGridViewColumnSortMode.Automatic;
            DataGridViewButtonColumn btndel = new DataGridViewButtonColumn();
            btndel.HeaderText = "Delete";
            btndel.Text = "Delete";
            btndel.Name = "btnDelete";
            btndel.UseColumnTextForButtonValue = true;
            dgvDimension.Columns.Add(btndel);
            
            dgvDimension.DataSource = _gridSource;
            
            //dgvDimension.Columns.Insert(5, btndel);
            //dgvDimension.Columns[0].Visible = false;
            //SqlCommand cmd = new SqlCommand("select dimension_id,length,width,height,piece_count from t_eics_dimension where slip_id=@slip_id order by create_date", sqlCon);
            //cmd.Parameters.AddWithValue("@slip_id", ViewEditWeightSlip.slip_id);
            ////cmd.Parameters.AddWithValue("@mawb_id", MAWB_id);
            //sqlCon.Open();

            //SqlDataAdapter daLocationDetail = new SqlDataAdapter(cmd);
            //dtDimDetail = new DataSet();
            //daLocationDetail.Fill(dtDimDetail, "dtDimDetail");
            //DataTable dtDimDetail_TB = CreateDimDetail_TB(dtDimDetail);
            //dgvDimension.DataSource = dtDimDetail_TB;

            //sqlCon.Close();


        }
        /// <summary>
        /// Save all modified/new rows in grid
        /// </summary>
        /// <returns></returns>
        private DialogResult CheckSaveChanged()
        {
            DialogResult result = System.Windows.Forms.DialogResult.No;
            bool isModified = false;
            for (int i = 0; i < _gridSource.Count; i++)
            {
                if (_gridSource[i].GetObjectSate() != OBJECT_STATE.None)
                {
                    isModified = true;
                    _gridSource[i].Device = GlobalVariable.user.Device;
                    _gridSource[i].AppId = GlobalVariable.user.ApplicationID;
                    _gridSource[i].UserId = GlobalVariable.user.UserID;
                    _gridSource[i].SlipId = ViewEditWeightSlip.slip_id;
                    if (_gridSource[i].GetObjectSate() == OBJECT_STATE.Insert)
                    {
                        _gridSource[i].DimensionNumber = i + 1;
                    }
                }
            }
            if (isModified)
            {
                result = CommonMessageBox.displayConfirmSave();
                if (result == System.Windows.Forms.DialogResult.Yes)
                {
                    _dataComponent.SaveChanges(_gridSource.ToList<ObjectContext>());
                    GetPcs();   // Create by por
                    this.DialogResult = DialogResult.Yes;
                }
                else
                {
                    this.DialogResult = DialogResult.No;
                    //GetPcs(); // Create by por
                }
            }
            return result;
            /*
            countpass = 0;
            for (int i = 0; i < dgvDimension.Rows.Count - 1; i++)
            {


                allpass = dgvDimension.Rows.Count - 1;
                string dim_id = dgvDimension.Rows[i].Cells[0].Value.ToString();
                //ถ้า dim_id = null แสดงว่า insert เป็นค่าใหม่
                if (dim_id.Equals(""))
                {

                    try
                    {
                        SqlCommand cmd = new SqlCommand();
                        cmd.CommandText = "c";
                        cmd.CommandType = CommandType.StoredProcedure;
                        cmd.Connection = sqlCon;
                        cmd.Parameters.AddWithValue("@in_vchApplicationID", appId);
                        cmd.Parameters.AddWithValue("@in_vchSlipID", ViewEditWeightSlip.slip_id);
                        cmd.Parameters.AddWithValue("@in_intDimensionNumber", i + 1);
                        cmd.Parameters.AddWithValue("@in_fltLength", dgvDimension.Rows[i].Cells[1].Value);
                        cmd.Parameters.AddWithValue("@in_fltWidth", dgvDimension.Rows[i].Cells[2].Value);
                        cmd.Parameters.AddWithValue("@in_fltHeight", dgvDimension.Rows[i].Cells[3].Value);
                        cmd.Parameters.AddWithValue("@in_intPieceCount", dgvDimension.Rows[i].Cells[4].Value);
                        cmd.Parameters.AddWithValue("@in_vchDevice", device);
                        cmd.Parameters.AddWithValue("@in_vchUserID", GlobalVariable.userName);

                        sqlCon.Open();
                        SqlDataAdapter da = new SqlDataAdapter(cmd);
                        datasetInsert = new DataSet();
                        da.Fill(datasetInsert, "InsertDimensionRecord");
                        string status = datasetInsert.Tables[0].Rows[0]["Status"].ToString();
                        string Messagest = datasetInsert.Tables[0].Rows[0]["Message"].ToString();
                        if (status == "PASS")
                        {
                            countpass = countpass + 1;
                        }
                        else
                        {
                            MessageBox.Show(Messagest);
                        }
                        sqlCon.Close();
                    }
                    catch (Exception objEx)
                    {
                        sqlCon.Close();
                        string str = objEx.Message;
                        MessageBox.Show(str);

                    }



                }

                    //เคสอัพเดท(มีค่า dim_id มา
                else
                {
                    try
                    {
                        SqlCommand cmd = new SqlCommand();
                        cmd.CommandText = "usp_UpdateDimensionRecord";
                        cmd.CommandType = CommandType.StoredProcedure;
                        cmd.Connection = sqlCon;
                        cmd.Parameters.AddWithValue("@in_vchApplicationID", appId);
                        cmd.Parameters.AddWithValue("@in_vchSlipID", ViewEditWeightSlip.slip_id);
                        cmd.Parameters.AddWithValue("@in_intDimensionNumber", i + 1);
                        cmd.Parameters.AddWithValue("@in_vchDimensionID", dim_id);
                        cmd.Parameters.AddWithValue("@in_fltLength", dgvDimension.Rows[i].Cells[1].Value);
                        cmd.Parameters.AddWithValue("@in_fltWidth", dgvDimension.Rows[i].Cells[2].Value);
                        cmd.Parameters.AddWithValue("@in_fltHeight", dgvDimension.Rows[i].Cells[3].Value);
                        cmd.Parameters.AddWithValue("@in_intPieceCount", dgvDimension.Rows[i].Cells[4].Value);
                        cmd.Parameters.AddWithValue("@in_vchDevice", device);
                        cmd.Parameters.AddWithValue("@in_vchUserID", GlobalVariable.userName);

                        sqlCon.Open();
                        SqlDataAdapter da = new SqlDataAdapter(cmd);
                        datasetUpdate = new DataSet();
                        da.Fill(datasetUpdate, "UpdateDimensionRecord");
                        string status = datasetUpdate.Tables[0].Rows[0]["Status"].ToString();
                        string Messagest = datasetUpdate.Tables[0].Rows[0]["Message"].ToString();
                        if (status == "PASS")
                        {
                            countpass = countpass + 1;
                        }
                        else
                        {
                            MessageBox.Show(Messagest);
                        }
                        sqlCon.Close();
                    }
                    catch (Exception objEx)
                    {
                        sqlCon.Close();
                        string str = objEx.Message;
                        MessageBox.Show(str);

                    }
                }
            }
            if (countpass == allpass)
            {
                //   MessageBox.Show("Save");
                this.Dispose();
            }

            // showdgvDimensionDisplay();
            */
        }
        /// <summary>
        /// set row number
        /// </summary>
        /// <param name="dgv"></param>
        private void setRowNumber(DataGridView dgv)
        {
            foreach (DataGridViewRow row in dgv.Rows)
            {
                if (row.Index == dgv.Rows.Count - 1)
                {
                    row.HeaderCell.Value = "";
                }
                else
                {
                    row.HeaderCell.Value = String.Format("{0}", row.Index + 1);
                }
            }
        }
        //kung
        private void dgvDimension_CurrentCellChanged(object sender, EventArgs e)
        {
            try
            {
                setRowNumber(dgvDimension);
            }
            catch (Exception ex)
            {
                CommonMessageBox.ShowMessageError(ex);
            }
        }
        //kung
        private void dgvDimension_Sorted(object sender, EventArgs e)
        {
            setRowNumber(dgvDimension);
        }
        

        //private DataTable CreateDimDetail_TB(DataSet ds)
        //{
        //    DataTable TLocationDetail = new DataTable();
        //    ///////////create head column/////////////////
        //    TLocationDetail.Columns.Add("dimension_id", typeof(string));
        //    TLocationDetail.Columns.Add("L", typeof(string));
        //    TLocationDetail.Columns.Add("W", typeof(string));
        //    TLocationDetail.Columns.Add("H", typeof(string));

        //    TLocationDetail.Columns.Add("PCS", typeof(string));

        //    ///////////////////////////////////////////////
        //    int row = dtDimDetail.Tables[0].Rows.Count;
        //    for (int i = 0; i < row; i++)
        //    {
        //        dimension_id = dtDimDetail.Tables[0].Rows[i]["dimension_id"].ToString().Trim();
        //        length = dtDimDetail.Tables[0].Rows[i]["length"].ToString().Trim();
        //        width = dtDimDetail.Tables[0].Rows[i]["width"].ToString().Trim();
        //        height = dtDimDetail.Tables[0].Rows[i]["height"].ToString().Trim();
        //        piece_count = dtDimDetail.Tables[0].Rows[i]["piece_count"].ToString().Trim();

        //        TLocationDetail.Rows.Add(dimension_id, length, width, height, piece_count);
        //    }
        //    return TLocationDetail;
        //}
    }
}
